// 引入express模块
const express = require('express');
const handleErrorMessage = require('./utils/handleErrorMessage.cjs');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

// 创建express应用
const app = express();

// 设置请求体大小限制，例如设置为10MB
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 相关中间件
app.use(bodyParser.json());
app.use(cors());

// 定义一个简单的路由
app.get('/', (req, res) => {
  res.send('Hello FrontEnd Error Monitoring!');
});

app.post("/upload", bodyParser.json({ type: 'application/octet-stream', limit: "100mb" }), (req, res) => {
  const form = req.body;
  fs.writeFile(path.resolve(__dirname, './uploads', form.fileName), form.file, (err) => {
    if (err) {
      res.status(500).send("保存文件时发生错误。");
    } else {
      res.status(200).send("文件上传成功。");
    }
  });
});

app.post("/sendErrorLog", (req, res) => {
  handleErrorMessage(req.body)
  res.send("success")
})

// 启动服务器，监听3000端口
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});